using UnityEngine;
using System;
using System.Linq;
using System.Reflection;

// ReSharper disable once CheckNamespace
public static class ModLog
{
    private enum LogLevel
    {
        [EnumDisplay("信息 - 输出所有日志")]
        Info = 0,

        [EnumDisplay("警告 - 仅输出警告和错误")]
        Warning = 1,

        [EnumDisplay("错误 - 仅输出错误")]
        Error = 2,

        [EnumDisplay("无 - 不输出任何日志")]
        // ReSharper disable once UnusedMember.Local
        Nothing = 3
    }

    // 静态字段，在静态构造函数中初始化
    public static readonly string ModName;

    [Config(Description = "日志输出级别")]
    // ReSharper disable once ConvertToConstant.Local
    private static readonly LogLevel LOGLevel = LogLevel.Info;

    // 静态构造函数
    static ModLog()
    {
        // 从程序集中寻找 ModBehaviour 类并使用其命名空间
        ModName = FindModBehaviourNamespace() ?? "UnknownMod";
    }

    /// <summary>
    /// 在当前程序集中查找 ModBehaviour 类并返回其命名空间
    /// </summary>
    private static string? FindModBehaviourNamespace()
    {
        try
        {
            // 获取当前程序集
            var assembly = Assembly.GetExecutingAssembly();
            
            // 查找所有从 ModBehaviour 派生的类型
            var modBehaviourTypes = assembly.GetTypes()
                .Where(t => t.IsClass && !t.IsAbstract && IsModBehaviour(t))
                .ToList();

            if (modBehaviourTypes.Count > 0)
            {
                // 使用第一个找到的 ModBehaviour 类的命名空间
                return modBehaviourTypes[0].Namespace;
            }

            // 如果没有找到 ModBehaviour，尝试查找名称包含 "ModBehaviour" 的类
            var fallbackType = assembly.GetTypes()
                .FirstOrDefault(t => t.IsClass && !t.IsAbstract && 
                                   (t.Name.Contains("ModBehaviour") || t.Name.Contains("Mod")));

            return fallbackType?.Namespace;
        }
        catch (Exception ex)
        {
            Debug.LogError($"[ModLog] 查找 ModBehaviour 时出错: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// 检查类型是否是 ModBehaviour 或其派生类
    /// </summary>
    private static bool IsModBehaviour(Type type)
    {
        // 遍历继承链查找 ModBehaviour
        var current = type;
        while (current != null && current != typeof(object))
        {
            if (current.Name == "ModBehaviour" || current.FullName?.Contains("ModBehaviour") == true)
            {
                return true;
            }
            current = current.BaseType;
        }
        return false;
    }

    public static void Info(string message)
    {
        if (LOGLevel <= LogLevel.Info)
        {
            Debug.Log($"[{ModName}] {message}");
        }
    }

    public static void Warning(string message)
    {
        if (LOGLevel <= LogLevel.Warning)
        {
            Debug.LogWarning($"[{ModName}] {message}");
        }
    }

    public static void Error(string message)
    {
        if (LOGLevel <= LogLevel.Error)
        {
            Debug.LogError($"[{ModName}] {message}");
        }
    }
}